package com.example.robertluozizhao.framecollectdemo.view.opengl;

import android.content.Context;
import android.opengl.GLSurfaceView;
import android.view.MotionEvent;

/**
 * Created by Lzz on 3/30/2020.
 */
/**
 * GLSurfaceView是专门用来绘制OpenGL ES图形的，但是它自己没有做多少工作，真正的绘制是由GLSurfaceView.Renderer来完成的
 * */
public class MyGLSurfaceView extends GLSurfaceView{

    private final MyGLRenderer mRenderer;

    public MyGLSurfaceView(Context context) {
        super(context);

        //创建OpenGL ES 2.0 的上下文
        setEGLContextClientVersion(2);

        mRenderer = new MyGLRenderer();

        // 设置Renderer 到 GLSurfaceView
        setRenderer(mRenderer);

        //设置GLSurfaceView绘制的方式
        //GLSurfaceView.RENDERMODE_WHEN_DIRTY 当有数据时才rendered
        //GLSurfaceView.RENDERMODE_CONTINUOUSLY 一直Render
        //OG001-006-001 设置GLSurfaceView的渲染模式
        setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY); // 注释掉，图形就可以自动旋转了

    }


    /**********************OG001-006 设置触摸监听事件******************************/
    /**
     * 在GLSurfaceView类中实现onTouchEvent()方法
     */
    private final float TOUCH_SCALE_FACTOR = 180.0f / 320;
    private float mPreviousX;
    private float mPreviousY;

    /**
     * 计算了图形旋转的角度
     * @param e
     * @return
     */
    @Override
    public boolean onTouchEvent(MotionEvent e) {
        // MotionEvent reports input details from the touch screen
        // and other input controls. In this case, you are only
        // interested in events where the touch position changed.

        float x = e.getX();
        float y = e.getY();

        switch (e.getAction()) {
            case MotionEvent.ACTION_MOVE:

                float dx = x - mPreviousX;
                float dy = y - mPreviousY;

                // reverse direction of rotation above the mid-line
                if (y > getHeight() / 2) {
                    dx = dx * -1 ;
                }

                // reverse direction of rotation to left of the mid-line
                if (x < getWidth() / 2) {
                    dy = dy * -1 ;
                }

                mRenderer.setAngle(
                        mRenderer.getAngle() +
                                ((dx + dy) * TOUCH_SCALE_FACTOR));

                //在计算完旋转的角度后，调用了requesetRender()，这是为了告诉renderer要渲染帧了。这样做的好处就是效率高，
                // 因为只有在旋转的时候才需要去渲染，其他时候不需要渲染。为了达到这种效果，我们需要设置GLSurfaceView的渲染模式
                requestRender();
        }

        mPreviousX = x;
        mPreviousY = y;
        return true;
    }
}
